// pages/site/choose-site/choose-site.js
var httpUtil = require('../../../utils/httpUtil.js');
var uiUtil = require('../../../utils/uiUtil.js');
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.min.js');
var key = "QR7BZ-UDZ3R-SS7WQ-WLPBD-76352-5YBB5";
var qqmapsdk = new QQMapWX({key: key});
const app = getApp();
var that;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    siteLists: {
      totalCount: null,
      pageCount: null,
      pageNo: "0",
      pageSize: "30",
      dataList: []
    },

    mchHome:null, //商户信息
    indexThat:null, //收货地址选择

    requestGoodsTask: null, //请求task
    isLoadingMore: false,
    enableLoadMore: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;
    let mchHome=JSON.parse(options.mchHome);
    that.setData({
      mchHome:mchHome
    })
    that.getSearchUsedAddress();
  },


  /**
   * 常用地址查询
   */
  getSearchUsedAddress() {
    let pageNo = (parseInt(that.data.siteLists.pageNo) + 1).toString();
    let pageSize = that.data.siteLists.pageSize;
    let dataList = that.data.siteLists.dataList;
    let totalCount = that.data.siteLists.totalCount;

    var lastRequestTask = that.data.requestGoodsTask;
    if (lastRequestTask) {
      try {
        lastRequestTask.abort()
      } catch (e) { }
    }

    var curPage = that.data.siteLists.pageNo
    if (curPage != 0 && (!that.data.enableLoadMore || that.data.isLoadingMore)) { //不可加载||正在加载
      return;
    }

    var requestTask = httpUtil.PostRequest("searchUsedAddress", {
      pageNo: pageNo,
      pageSize: pageSize
    }, {
        success(res) {
          if (0 == that.data.siteLists.totalCount) {
            res.dataList = res.dataList || []
            if (res.dataList.length == 0) { //内容为空
              that.setData({
                fail: true
              })
            }
          } else {
            res.dataList = dataList.concat(res.dataList || []);
          }
          res=that.isDistance(res);
          that.setData({
            siteLists: res,
            enableLoadMore: res.dataList.length < res.totalCount,
          })
        },
        fail(code, res) {
          that.setData({
            enableLoadMore: false,
          })
          uiUtil.showToast(res);
        },
        complete() {
          that.setData({
            isLoadingMore: false
          })
        }
      })
    that.setData({
      requestGoodsTask: requestTask
    })
  },

  //判断配送距离
  isDistance(res,fun){
    var resLocation=[];
    for(let i=0;i<res.dataList.length;i++){
      resLocation.push({
        latitude:res.dataList[i].lat,
        longitude:res.dataList[i].lng
      })
    }
    qqmapsdk.calculateDistance({
      mode: "straight",
      from:{
        latitude: that.data.mchHome.lat,
        longitude: that.data.mchHome.lng
      },
      to:resLocation,
      success: function (e) {
        for(let i=0;i<res.dataList.length;i++){
          res.dataList[i].distance=(e.result.elements[i].distance/1000);
        }
      },
      fail: function (e) {}
    });
    return res;
  },


  /**
   * 收货地址选择
   */
  indexChange(e){
    let index = e.currentTarget.dataset.index;
    let item = e.currentTarget.dataset.item;
    that.setData({
      indexThat:index
    })
    setTimeout(function(){
      var pages = getCurrentPages();
      var lastPage = pages[pages.length - 2];
      if (lastPage.route == "pages/index/order/order-pre/order-pre") {
        lastPage.setData({
          "value.site":item
        })
        wx.navigateBack({
          delta: 1,
        });
      }
    }, 300)
  },

  /**
   * 提示收货地址超出配送范围
   */
  hintSite(){
    uiUtil.showToast("该地址超出配送范围");
  },

  /**
   * 滑动到底部
   */
  onReachBottom: function () {
    that.getSearchUsedAddress();
  },

  /**
  * 回调
  */
  onResultRegisterSuccess(){
    that.setData({
      siteLists: {
        totalCount: null,
        pageCount: null,
        pageNo: "0",
        pageSize: "30",
        dataList: []
      },
      requestGoodsTask: null, //请求task
      isLoadingMore: false,
      enableLoadMore: true
    })
    that.getSearchUsedAddress();
  }
})